const api = require('../../utils/api.js');
const storage = require('../../utils/storage.js');

Page({
  data: {
    activityId: 0,
    activityTitle: '',
    activityDetails: '',
    isLoading: false
  },

  onLoad(options) {
    console.log('📱 =============== 活动编辑页面加载 ===============');
    
    // 获取活动ID
    const activityId = parseInt(options.id);
    if (!activityId) {
      wx.showToast({
        title: '活动ID不存在',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      return;
    }

    // 获取活动标题和详情（从URL参数）
    const title = decodeURIComponent(options.title || '');
    const details = decodeURIComponent(options.details || '');

    console.log('📝 活动ID:', activityId);
    console.log('📝 活动标题:', title);
    console.log('📝 活动详情:', details);

    this.setData({
      activityId: activityId,
      activityTitle: title,
      activityDetails: details
    });
  },

  onShow() {
    // 🔔 自动初始化通知组件
    const app = getApp();
    app.autoInitNotification();
  },

  /**
   * 标题输入
   */
  onTitleInput(e) {
    this.setData({
      activityTitle: e.detail.value
    });
  },

  /**
   * 详情输入
   */
  onDetailsInput(e) {
    this.setData({
      activityDetails: e.detail.value
    });
  },

  /**
   * 保存活动
   */
  saveActivity() {
    console.log('💾 =============== 保存活动 ===============');

    // 验证输入
    if (!this.data.activityTitle.trim()) {
      wx.showToast({
        title: '请输入活动标题',
        icon: 'none'
      });
      return;
    }

    if (!this.data.activityDetails.trim()) {
      wx.showToast({
        title: '请输入活动描述',
        icon: 'none'
      });
      return;
    }

    // 显示加载状态
    this.setData({ isLoading: true });

    wx.showLoading({
      title: '保存中...',
      mask: true
    });

    // 调用编辑活动API
    api.editActivity(
      this.data.activityId,
      this.data.activityTitle.trim(),
      this.data.activityDetails.trim()
    ).then(response => {
      console.log('✅ 活动编辑成功:', response);
      
      wx.hideLoading();
      
      wx.showToast({
        title: response.message || '编辑成功',
        icon: 'success',
        duration: 2000
      });

      // 延迟返回，让用户看到成功提示
      setTimeout(() => {
        wx.navigateBack({
          delta: 1
        });
      }, 2000);
      
    }).catch(error => {
      console.error('❌ 活动编辑失败:', error);
      
      wx.hideLoading();
      
      wx.showToast({
        title: error.message || '编辑失败，请重试',
        icon: 'none',
        duration: 2000
      });
      
      this.setData({ isLoading: false });
    });
  }
});

